import { getStore, setStore } from '@/utils/util/store'
import { isURL, validatenull } from '@/utils/util/validate'
import {
    loginByMobile,
    loginBySocial,
    loginByUsername,
    getUserInfo,
    logout,
    refreshToken,
    switchPost, loginByXindunCode, loginByZj3Portal
} from '@/api/login'
import { deepClone } from '@/utils/util'
import { aesEncrypt } from '@/utils/util/encryption'
import website from '@/const/website'
// import { resetRouter } from '@/router/router'
import { getUserTopMenu, getUserMenuTree } from '@/API/user-menu'
import router from "@/router";

function addPath(ele, first) {
    const menu = website.menu
    const propsConfig = menu.props
    const propsDefault = {
        label: propsConfig.label || 'name',
        path: propsConfig.path || 'path',
        icon: propsConfig.icon || 'icon',
        children: propsConfig.children || 'children'
    }
    const icon = ele[propsDefault.icon]
    ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon
    const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0
    if (!isChild) ele[propsDefault.children] = []
    if (!isChild && first && !isURL(ele[propsDefault.path])) {
        ele[propsDefault.path] = ele[propsDefault.path] + '/index'
    } else {
        ele[propsDefault.children].forEach(child => {
            addPath(child)
        })
    }
}

const sessionType = undefined // 设置为 undefined 则使用 localStorage, 使用 'session' 使用 sessionStorage，sessionStorage不能跨标签页，打开新标签页则需要重新登录，可以实现每个tab页不同用户登录

const user = {
    state: {
        userInfo: getStore({
            name: 'userInfo'
        }) || {},
        permissions: getStore({
            name: 'permissions'
        }) || [],
        //用户当前岗位
        post: getStore({
            name: 'post'
        }) || {},
        //用户所有岗位
        posts: getStore({
            name: 'posts'
        }) || [],
        menu: getStore({
            name: 'menu'
        }) || [],
        leftMenu: getStore({
            name: 'leftMenu'
        }) || [],
        access_token: getStore({
            name: 'access_token'
        }) || '',
        refresh_token: getStore({
            name: 'refresh_token'
        }) || '',
        idaasId: getStore({
            name: 'idaasId'
        }) || '',
        ltpaToken: getStore({
            name: 'ltpaToken'
        }) || '',
        xindunToken: getStore({
            name: 'xindunToken'
        }) || '',
        isUserLoading: false,
    },
    actions: {
        // 根据用户名登录
        LoginByUsername({ commit }, userInfo) {
            if (website.passwordEnc) {
                userInfo.password = aesEncrypt(userInfo.password, website.encPassword)
            }
            return new Promise((resolve, reject) => {
                loginByUsername(userInfo.username, userInfo.password, userInfo.code, userInfo.randomStr).then(response => {
                    const data = response.data
                    commit('SET_ACCESS_TOKEN', data.access_token)
                    commit('SET_REFRESH_TOKEN', data.refresh_token)
                    commit('CLEAR_LOCK')
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 根据手机号登录
        LoginByPhone({ commit }, userInfo) {
            return new Promise((resolve, reject) => {
                loginByMobile(userInfo.mobile, userInfo.code).then(response => {
                    const data = response.data
                    commit('SET_ACCESS_TOKEN', data.access_token)
                    commit('SET_REFRESH_TOKEN', data.refresh_token)
                    commit('CLEAR_LOCK')
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 根据OpenId登录
        LoginBySocial({ commit }, param) {
            return new Promise((resolve, reject) => {
                loginBySocial(param.state, param.code).then(response => {
                    const data = response.data
                    commit('SET_ACCESS_TOKEN', data.access_token)
                    commit('SET_REFRESH_TOKEN', data.refresh_token)
                    commit('CLEAR_LOCK')
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        LoginByZj3Portal({ commit }, param) {
            return new Promise((resolve, reject) => {
                loginByZj3Portal(param.code).then(response => {
                    localStorage.clear();
                    console.log(response)
                    const data = response.data
                    // console.log('LoginByZj3Portal', data);

                    commit('SET_ACCESS_TOKEN', data.access_token)
                    commit('SET_REFRESH_TOKEN', data.refresh_token)
                    commit('CLEAR_LOCK')

                    commit('SET_IDAAS_ID', data.username)
                    commit('SET_LTPA_TOKEN', data.ltpaToken)

                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        LoginByXindunCode({ commit }, param) {
            return new Promise((resolve, reject) => {
                loginByXindunCode(param.code).then(response => {
                    console.log(response)

                    const data = response.data

                    commit('SET_ACCESS_TOKEN', data.access_token)
                    commit('SET_REFRESH_TOKEN', data.refresh_token)
                    commit('CLEAR_LOCK')

                    commit('SET_IDAAS_ID', param.userCode)
                    commit('SET_XINDUN_TOKEN', param.access_token)

                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 刷新token
        RefreshToken({ commit, state }) {
            return new Promise((resolve, reject) => {
                refreshToken(state.refresh_token).then(response => {
                    const data = response.data
                    commit('SET_ACCESS_TOKEN', data.access_token)
                    commit('SET_REFRESH_TOKEN', data.refresh_token)
                    commit('CLEAR_LOCK')
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        SwitchPost({ commit, state }, params) {
            return new Promise((resolve, reject) => {
                commit('SET_USER_LOADING', true)
                switchPost(params.userId, params.username, params.defaultPostId).then(response => {
                    const data = response.data.data
                    commit('SET_USER_INFO', data.sysUser)
                    commit('SET_POST', data.post)
                    commit('SET_POSTS', data.posts || [])
                    commit('SET_PERMISSIONS', data.permissions || [])
                    commit('DEL_ALL_TAG')
                    commit('CLEAR_LOCK')
                    resolve()
                }).catch(error => {
                    reject(error)
                }).finally(() => {
                    commit('SET_USER_LOADING', false)
                })
            })
        },
        // 查询用户信息
        GetUserInfo({ commit }) {
            return new Promise((resolve, reject) => {
                commit('SET_USER_LOADING', true)
                getUserInfo().then((res) => {
                    const data = res.data.data || {}
                    commit('SET_USER_INFO', data.sysUser)
                    commit('SET_POST', data.post)
                    commit('SET_POSTS', data.posts || [])
                    commit('SET_PERMISSIONS', data.permissions || [])
                    resolve(data)
                }).catch(() => {
                    reject()
                }).finally(() => {
                    commit('SET_USER_LOADING', false)
                })
            })
        },
        // 登出
        LogOut({ commit }) {
            return new Promise((resolve, reject) => {
                logout().then(() => {
                    router.replace("/login")
                    commit('SET_MENU', [])
                    commit('SET_PERMISSIONS', [])
                    commit('SET_USER_INFO', {})
                    commit('SET_ACCESS_TOKEN', '')
                    commit('SET_REFRESH_TOKEN', '')
                    commit('SET_POST', {})
                    commit('SET_POSTS', [])
                    commit('DEL_ALL_TAG')
                    commit('CLEAR_LOCK')
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获取系统菜单
        GetMenu({ commit }, obj) {
            // 记录用户点击顶部信息，保证刷新的时候不丢失
            if (obj) {
                commit('LIKE_TOP_MENUID', obj)
            }

            return new Promise(resolve => {
                getUserMenuTree(obj.id).then((res) => {
                    const data = res.data.data
                    const menu = deepClone(data)
                    menu.forEach(ele => {
                        addPath(ele)
                    })
                    const type = obj.type
                    if (!validatenull(type)){
                        if (type === '-1') {
                            commit('SET_MENU', { type, menu })
                        } else if (type === '0') {
                            commit('SET_LEFT_MENU', { type, menu })
                        }
                    }

                    resolve(menu)
                })
            })
        },
        //顶部菜单
        GetTopMenu() {
            return new Promise(resolve => {
                getUserTopMenu().then((res) => {
                    const data = res.data.data || []
                    resolve(data)
                })
            })
        }
    },
    mutations: {
        SET_ACCESS_TOKEN: (state, access_token) => {
            state.access_token = access_token
            setStore({
                name: 'access_token',
                content: access_token,
                type: sessionType
            })
        },
        SET_REFRESH_TOKEN: (state, rfToken) => {
            state.refresh_token = rfToken
            setStore({
                name: 'refresh_token',
                content: rfToken,
                type: sessionType
            })
        },
        SET_USER_INFO: (state, userInfo) => {
            state.userInfo = userInfo
            setStore({
                name: 'userInfo',
                content: userInfo,
                type: sessionType
            })
        },
        SET_USER_LOADING: (state, flag) => {
            state.isUserLoading = flag
        },
        SET_POST: (state, post) => {
            state.post = post
            setStore({
                name: 'post',
                content: post,
                type: sessionType
            })
        },
        SET_MENU: (state, params = {}) => {
            const { menu } = params
            // type  -1 all, 0 left menu, 2 top menu, 1 button
            state.menu = menu
            setStore({
                name: 'menu',
                content: menu,
                type: sessionType
            })
        },
        SET_LEFT_MENU: (state, params = {}) => {
            const { menu } = params
            state.leftMenu = menu
            setStore({
                name: 'leftMenu',
                content: menu,
                type: sessionType
            })
        },
        SET_POSTS: (state, posts) => {
            state.posts = posts
        },
        SET_PERMISSIONS: (state, permissions) => {
            const list = {}
            for (let i = 0; i < permissions.length; i++) {
                list[permissions[i]] = true
            }

            state.permissions = list
            setStore({
                name: 'permissions',
                content: list,
                type: sessionType
            })
        },
        SET_IDAAS_ID: (state, idaasId) => {
            state.idaasId = idaasId
            setStore({
                name: 'idaasId',
                content: idaasId,
                type: sessionType
            })
        },
        SET_LTPA_TOKEN: (state, ltpaToken) => {
            state.ltpaToken = ltpaToken
            setStore({
                name: 'ltpaToken',
                content: state.ltpaToken,
                type: sessionType
            })
        },
        SET_XINDUN_TOKEN: (state, xindunToken) => {
            state.xindunToken = xindunToken
            setStore({
                name: 'xindunToken',
                content: state.xindunToken,
                type: sessionType
            })
        },
    }

}
export default user

